package com.dr.controller;

import com.alibaba.fastjson.JSONObject;
import com.dr.pojo.JwtAuthenticationRequest;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.AuthenticationException;
import java.io.*;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class AuthenticationController {

    private static final Map<String,Object> map = new HashMap<>();


    @PostMapping(value = "/auth")
    public String auth() throws AuthenticationException {

        String userNname = "huhu";
        String passWord = "huhu123456";
        String url = "http://cfda-dr.yiweiimage.com/auth";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username",userNname);
        jsonObject.put("password",passWord);
        JSONObject jsonObject1 = httpPost(url, jsonObject, false);
        if(jsonObject1.get("msg").equals("登陆成功")){//说明登录成功
            try {
            System.out.println("成功");
            //编写上传逻辑
            String token = "Bearer  " +  jsonObject1.get("token");
            updateLoadImg(token);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "上传成功";
        }else{//登录失败
            return "失败";
        }
    }


    public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    public void updateLoadImg(String token) throws Exception {
        System.out.println(token);
        //String token = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJodWh1IiwiZXhwIjoxNjU5MDYzNTgwLCJ1c2VyaWQiOjE1LCJpYXQiOjE2NTg0NTg3ODB9.WTc9z-NIo2O78eU3tzsaLoaEFacT2U14aswIIK_06n1tAkqGe1eG43V6u356ksCoWlS_zRH8qEA7iJAQjcLt-A";
        String path = "C:\\Users\\王子群\\Desktop\\依未科技桌面文件\\";
        List<String> img = getImg(path);
        for (String s : img) {
            File file = new File(path+s);
            //File文件转MultipartFile
            FileInputStream input = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
            httpPostFile(multipartFile,token);
        }

    }

    public void httpPostFile(MultipartFile file,String token) {
        String url = "http://cfda-dr.yiweiimage.com/imgs/upload";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Authorization",token);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            String filename = file.getOriginalFilename();
            builder.addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, filename);
            // 如果需要，传递额外参数
            // StringBody fileName = new StringBody("文件名称", ContentType.MULTIPART_FORM_DATA);
            // StringBody userName = new StringBody("用户名", ContentType.MULTIPART_FORM_DATA);
            // builder.addPart("fileName", fileName);
            // builder.addPart("userName", userName);

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println("结果：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<String> getImg(String path){
        List<String> list = new ArrayList<>();
        File file1 = new File(path);
        if (file1.exists()) {
            File[] files = file1.listFiles();
            for (File file2:files){
                if (file2.getName().indexOf("jpg")!=-1){
                    if(map.get(file2.getName()) == null){
                        list.add(file2.getName());
                        map.put(file2.getName(),file2.getName());
                    }
                }
            }
        }
        return list;
    }






}
